<template>
  <div class="orders-container">
    <div class="orders-header">
      <h1 class="page-title">我的订单</h1>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="下单确认" name="confirm">
          <div class="orders-steps">
            <el-steps :active="2" simple>
              <el-step title="确认购物车" icon="ShoppingCart" />
              <el-step title="确认订单" icon="Document" />
              <el-step title="支付" icon="CreditCard" />
              <el-step title="完成" icon="CircleCheck" />
            </el-steps>
          </div>
        </el-tab-pane>
        <el-tab-pane label="我的订单列表" name="list"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 下单确认面板 -->
    <div v-if="activeTab === 'confirm'" class="order-form">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>收货信息</span>
          </div>
        </template>
        <el-form :model="orderForm" label-width="80px">
          <el-form-item label="收货人">
            <el-input v-model="orderForm.linkUser" placeholder="请输入收货人姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="orderForm.linkPhone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="收货地址">
            <el-input v-model="orderForm.linkAddress" type="textarea" placeholder="请输入详细地址"></el-input>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 订单商品列表 -->
      <el-card class="box-card order-items">
        <template #header>
          <div class="card-header">
            <span>订单商品</span>
          </div>
        </template>
        <div v-if="selectedItems.length > 0" class="items-list">
          <div class="items-header">
            <span class="item-name">商品</span>
            <div class="item-price" style="display: none;">单价</div>
            <span class="item-quantity">数量</span>
            <span class="item-total">小计</span>
          </div>
          <div 
            v-for="item in selectedItems" 
            :key="item.id" 
            class="order-item"
          >
            <div class="item-info">
              <div class="item-image">
                <el-image :src="item.cover" fit="cover" />
              </div>
              <div class="item-details">
                <div class="item-name-container">
                  <div class="item-title">{{ item.title }}</div>
                  <div class="item-spec" v-if="item.specName">规格：{{ item.specName }}</div>
                </div>
                <div class="item-price-tag">
                  <div class="price-tag">¥{{ item.price.toFixed(2) }}</div>
                  <div class="count-tag">x{{ item.quantity }}</div>
                </div>
              </div>
            </div>
            <div class="item-price" style="display: none;">
              <div class="price-label">单价</div>
              <span class="price">¥{{ item.price.toFixed(2) }}</span>
            </div>
            <div class="item-quantity">
              {{ item.quantity }}
            </div>
            <div class="item-total">
              <span class="price total">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
            </div>
          </div>
        </div>
        <el-empty v-else description="没有选择任何商品"></el-empty>
      </el-card>
      
      <!-- 订单小结 -->
      <el-card class="box-card order-summary">
        <template #header>
          <div class="card-header">
            <span>订单小结</span>
          </div>
        </template>
        <div class="summary-content">
          <div class="summary-item">
            <span>商品总数：</span>
            <span>{{ totalItems }} 件</span>
          </div>
          <div class="summary-item">
            <span>商品总价：</span>
            <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>配送费用：</span>
            <span class="price">¥0.00</span>
          </div>
          <div class="summary-divider"></div>
          <div class="summary-item total">
            <span>订单总价：</span>
            <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
        </div>
      </el-card>
      
      <!-- 订单操作 -->
      <div class="order-actions">
        <el-button @click="goBack">返回购物车</el-button>
        <el-button type="primary" @click="submitOrder" :loading="submitting">提交订单</el-button>
      </div>
    </div>

    <!-- 订单列表面板 -->
    <div v-else-if="activeTab === 'list'" class="order-list-panel">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
        <div class="loading-text">正在加载订单信息...</div>
      </div>
      
      <el-empty v-else-if="orderList.length === 0" 
        description="暂无订单记录" 
        :image-size="120"
      >
        <template #extra>
          <el-button type="primary" @click="$router.push('/userWeb/home')" round>
            去购物
          </el-button>
        </template>
      </el-empty>
      
      <div v-else class="order-list">
        <!-- 直接显示原始订单数据 -->
        <div v-for="order in orderList" :key="order.id" class="order-card">
          <el-card shadow="hover" class="full-width">
            <template #header>
              <div class="order-card-header">
                <div class="order-info">
                  <span class="order-no">订单号：{{ order.order_no }}</span>
                  <span class="order-time">{{ order.create_time }}</span>
                </div>
                <div class="order-status">
                  <el-tag 
                    :type="getOrderStatusTag(order.state)" 
                    size="small" 
                    effect="dark" 
                    class="status-tag"
                  >
                    {{ order.state }}
                  </el-tag>
                </div>
              </div>
            </template>
            
            <div class="order-goods">
              <div class="order-good-item">
                <div class="good-image">
                  <el-image 
                    :src="getImageUrl(order.imgs)" 
                    fit="cover"
                    @click="goToProduct(order.good_id)"
                  />
                </div>
                <div class="good-info">
                  <div class="good-name-container">
                    <div class="good-name" @click="goToProduct(order.good_id)">{{ order.good_name || '未知商品' }}</div>
                    <!-- <div class="good-spec" v-if="order.standard">规格：{{ order.standard }}</div> -->
                  </div>
                  <div class="good-price-tag">
                    <div class="price-tag">¥{{ Number(order.total_price / order.count || 0).toFixed(2) }}</div>
                    <div class="count-tag">x{{ order.count || 1 }}</div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="order-footer">
              <div class="order-amount">
                <span class="amount-text">共 {{ order.count || 1 }} 件商品，总计：</span>
                <span class="amount-price">¥{{ Number(order.total_price || 0).toFixed(2) }}</span>
              </div>
              <div class="order-actions">
                <el-button 
                  v-if="order.state === '已发货'" 
                  size="small" 
                  type="primary" 
                  round
                  @click="confirmReceive(order.order_no)"
                >
                  确认收货
                </el-button>
                <el-button 
                  v-if="order.state === '待付款'" 
                  size="small" 
                  type="success" 
                  round
                  @click="payOrder(order.order_no)"
                >
                  立即支付
                </el-button>
                <!-- <el-button 
                  size="small"
                  plain
                  round
                  @click="viewOrderDetail(order.order_no)"
                >
                  订单详情
                </el-button> -->
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserWebOrders'
}
</script>

<script setup>
import { ref, computed, onMounted, onBeforeMount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';

const router = useRouter();
const route = useRoute();
const activeTab = ref('confirm');
const selectedItems = ref([]);
const submitting = ref(false);
const loading = ref(false);
const orderList = ref([]);

// 订单表单
const orderForm = ref({
  linkUser: '',
  linkPhone: '',
  linkAddress: '',
});

// 后端服务器基础URL
const baseUrl = 'http://localhost:9191';

// 处理图片URL的函数
const getImageUrl = (imgPath) => {
  if (!imgPath) return '';
  
  // 如果路径以http或https开头，说明是完整的URL，直接返回
  if (imgPath.startsWith('http://') || imgPath.startsWith('https://')) {
    return imgPath;
  }
  
  // 如果路径以/file/开头，需要拼接后端服务器地址
  if (imgPath.startsWith('/file/')) {
    return `${baseUrl}${imgPath}`;
  }
  
  // 其他情况直接拼接
  return `${baseUrl}/file/${imgPath}`;
};

// 处理订单状态标签颜色
const getOrderStatusTag = (status) => {
  switch (status) {
    case '待付款':
      return 'warning';
    case '已支付':
      return 'success';
    case '已发货':
      return 'primary';
    case '已收货':
      return 'success';
    case '已取消':
      return 'info';
    default:
      return '';
  }
};

// 总数量
const totalItems = computed(() => {
  return selectedItems.value.reduce((total, item) => total + item.quantity, 0);
});

// 总价格
const totalPrice = computed(() => {
  return selectedItems.value.reduce((total, item) => total + (item.price * item.quantity), 0);
});

// 处理标签页点击
const handleTabClick = (tab) => {
  if (tab.props.name === 'list') {
    fetchOrderList();
  } else if (tab.props.name === 'confirm') {
    fetchSelectedItems();
  }
};

// 获取购物车选中的商品
const fetchSelectedItems = async () => {
  try {
    // 从sessionStorage中获取选中的商品
    const items = sessionStorage.getItem('selectedItems');
    if (items) {
      selectedItems.value = JSON.parse(items);
    } else {
      ElMessage.warning('没有选中的商品，请先在购物车中选择商品');
      router.push('/userWeb/cart');
      return;
    }
    
    // 获取用户信息
    await fetchUserInfo();
  } catch (error) {
    console.error('获取选中商品失败:', error);
    ElMessage.error('获取选中商品失败，请返回购物车重新选择');
  }
};

// 获取用户详细信息
const fetchUserInfo = async () => {
  try {
    // 从sessionStorage获取基本用户信息
    const userStr = sessionStorage.getItem('user');
    if (!userStr) {
      ElMessage.warning('请先登录');
      router.push('/login');
      return;
    }
    
    const user = JSON.parse(userStr);
    
    // 调用后端接口获取用户详细信息
    const response = await request.get(`/userinfo/${user.username}`);
    
    if (response && response.code === '200' && response.data) {
      const userData = response.data;
      
      // 更新订单表单信息
      orderForm.value = {
        linkUser: userData.nickname || user.nickname || '',
        linkPhone: userData.phone || '',
        linkAddress: userData.address || '',
      };
    } else {
      // 如果获取详细信息失败，使用基本信息
      orderForm.value = {
        linkUser: user.nickname || '',
        linkPhone: '',
        linkAddress: '',
      };
    }
  } catch (error) {
    console.error('获取用户详细信息失败:', error);
    ElMessage.error('获取用户信息失败，请确保您已登录');
  }
};

// 返回购物车
const goBack = () => {
  router.push('/userWeb/cart');
};

// 提交订单
const submitOrder = async () => {
  if (!orderForm.value.linkUser) {
    ElMessage.warning('请填写收货人姓名');
    return;
  }
  if (!orderForm.value.linkPhone) {
    ElMessage.warning('请填写联系电话');
    return;
  }
  if (!orderForm.value.linkAddress) {
    ElMessage.warning('请填写收货地址');
    return;
  }
  
  ElMessageBox.confirm('确认提交订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    submitting.value = true;
    try {
      // 从sessionStorage获取用户信息
      const userStr = sessionStorage.getItem('user');
      if (!userStr) {
        ElMessage.warning('请先登录');
        router.push('/login');
        return;
      }
      const user = JSON.parse(userStr);
      
      // 准备订单数据
      const order = {
        userId: user.id, // 用户ID
        totalPrice: totalPrice.value, // 订单总价
        linkUser: orderForm.value.linkUser, // 收货人
        linkPhone: orderForm.value.linkPhone, // 联系电话
        linkAddress: orderForm.value.linkAddress, // 收货地址
        state: '已支付', // 订单状态
        goods: JSON.stringify(selectedItems.value.map(item => {
          // 确保规格名称正确，不要使用默认值"默认规格"，除非真的是这个值
          // 根据数据库中的good_standard表，需要使用正确的规格名称
          return {
            id: item.productId, // 商品ID
            standard: item.specName || '', // 使用商品本身的规格名称，如果为空则使用空字符串
            num: item.quantity // 数量
          };
        }))
      };
      
      // 如果购物车中的商品有cartId，可以添加
      const firstItem = selectedItems.value.find(item => item.id);
      if (firstItem) {
        order.cartId = firstItem.id;
      }
      
      // 调用后端接口创建订单
      const response = await request.post('/api/order', order);
      
      if (response && response.code === '200') {
        ElMessage.success('订单提交成功！');
        
        // 清空选中的商品
        sessionStorage.removeItem('selectedItems');
        
        // 切换到订单列表页签并刷新
        activeTab.value = 'list';
        await fetchOrderList();
        submitting.value = false;
      } else {
        ElMessage.error(response?.msg || '提交订单失败');
        submitting.value = false;
      }
    } catch (error) {
      console.error('提交订单失败:', error);
      ElMessage.error('提交订单失败，请稍后再试');
      submitting.value = false;
    }
  }).catch(() => {
    // 用户取消操作，不做处理
  });
};

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true;
  try {
    // 从sessionStorage获取用户信息
    const userStr = sessionStorage.getItem('user');
    if (!userStr) {
      ElMessage.warning('请先登录');
      router.push('/login');
      return;
    }
    const user = JSON.parse(userStr);
    
    // 调用后端接口获取用户订单列表
    const response = await request.get(`/api/order/userid/${user.id}`);
    
    if (response && response.code === '200') {
      orderList.value = response.data || [];
    } else {
      ElMessage.error(response?.msg || '获取订单列表失败');
      orderList.value = [];
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败，请稍后再试');
    orderList.value = [];
  } finally {
    loading.value = false;
  }
};

// 确认收货
const confirmReceive = async (order_no) => {
  try {
    ElMessageBox.confirm('确认已收到商品吗？', '确认收货', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const response = await request.get(`/api/order/received/${order_no}`);
      
      if (response && response.code === '200') {
        ElMessage.success('确认收货成功');
        fetchOrderList(); // 刷新订单列表
      } else {
        ElMessage.error(response?.msg || '确认收货失败');
      }
    });
  } catch (error) {
    console.error('确认收货失败:', error);
    ElMessage.error('确认收货失败，请稍后再试');
  }
};

// 支付订单
const payOrder = async (order_no) => {
  try {
    ElMessageBox.confirm('确认支付该订单吗？', '订单支付', {
      confirmButtonText: '确认支付',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const response = await request.get(`/api/order/paid/${order_no}`);
      
      if (response && response.code === '200') {
        ElMessage.success('支付成功');
        fetchOrderList(); // 刷新订单列表
      } else {
        ElMessage.error(response?.msg || '支付失败');
      }
    });
  } catch (error) {
    console.error('支付订单失败:', error);
    ElMessage.error('支付订单失败，请稍后再试');
  }
};

// 跳转到商品详情
const goToProduct = (productId) => {
  router.push(`/userWeb/product/${productId}`);
};

onBeforeMount(() => {
  // 检查路由参数，如果是从订单列表导航栏点击过来的，直接显示订单列表
  if (route.query.showList === 'true') {
    activeTab.value = 'list';
  }
});

onMounted(() => {
  if (activeTab.value === 'confirm') {
    fetchSelectedItems();
  } else {
    fetchOrderList();
  }
});
</script>

<style scoped>
.orders-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.orders-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  margin: 0 0 20px;
  color: #333;
}

.orders-steps {
  margin: 20px 0;
}

.order-form {
  margin-top: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

/* 订单商品列表样式 */
.items-header {
  display: grid;
  grid-template-columns: 70% 10% 20%;
  background-color: #f5f7fa;
  padding: 15px;
  font-weight: bold;
  text-align: center;
  border-radius: 4px;
}

.order-item {
  display: grid;
  grid-template-columns: 70% 10% 20%;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  align-items: center;
  text-align: center;
}

.item-info, .good-info {
  display: flex;
  align-items: center;
  text-align: left;
}

.item-image, .good-image {
  width: 80px;
  height: 80px;
  overflow: hidden;
  margin-right: 10px;
  border: 1px solid #eee;
}

.item-image .el-image, .good-image .el-image {
  width: 100%;
  height: 100%;
}

.item-details {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.item-name-container, .good-name-container {
  flex: 1;
  padding-right: 15px;
  max-width: calc(100% - 90px);
}

.item-title, .good-name {
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  cursor: pointer;
}

.item-title:hover, .good-name:hover {
  color: #409EFF;
}

.item-spec, .good-spec {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.item-price-tag, .good-price-tag {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-top: 6px;
  min-width: 80px;
}

.price-tag {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
  text-align: right;
}

.count-tag {
  background-color: #f0f0f0;
  color: #666;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  text-align: center;
  min-width: 36px;
}

.item-price {
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

.item-price .price-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.price {
  color: #ff4d4f;
  font-weight: bold;
}

.good-price {
  font-size: 12px;
  color: #666;
  display: flex;
  flex-direction: column;
  margin-top: 4px;
}

.good-price div {
  margin-bottom: 2px;
}

.quantity {
  margin-left: 4px;
}

.total {
  font-size: 16px;
}

/* 订单小结样式 */
.summary-content {
  padding: 10px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
}

.summary-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 10px 0;
}

.summary-item.total {
  font-weight: bold;
  font-size: 16px;
}

/* 订单操作 */
.order-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.order-actions .el-button {
  margin-left: 10px;
}

/* 订单列表样式 */
.order-list {
  margin-top: 20px;
}

.order-card {
  margin-bottom: 20px;
  transition: transform 0.2s ease;
}

.order-card:hover {
  transform: translateY(-2px);
}

.full-width {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.order-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  flex-direction: column;
}

.order-no {
  font-weight: bold;
  margin-bottom: 5px;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-goods {
  margin-top: 10px;
  border-top: 1px dashed #eee;
  padding-top: 15px;
}

.order-good-item {
  display: flex;
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 6px;
  background-color: #f9f9f9;
  transition: background-color 0.2s ease;
}

.order-good-item:hover {
  background-color: #f1f1f1;
}

.order-good-item .good-image {
  flex-shrink: 0;
}

.order-good-item .good-name {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-good-item:last-child {
  margin-bottom: 0;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.order-amount {
  display: flex;
  align-items: center;
}

.amount-text {
  margin-right: 5px;
  color: #666;
}

.amount-price {
  font-size: 18px;
  color: #ff6b6b;
  font-weight: bold;
}

.order-actions .el-button {
  margin-left: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.order-actions .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.loading-container {
  padding: 30px;
}

.loading-text {
  text-align: center;
  color: #909399;
  margin-top: 15px;
  font-size: 14px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .items-header,
  .order-item {
    grid-template-columns: 60% 15% 25%;
  }
  
  .item-price .price {
    word-break: break-all;
    font-size: 13px;
  }
  
  .item-image, .good-image {
    width: 60px;
    height: 60px;
  }
  
  .order-footer {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .order-amount {
    margin-bottom: 10px;
  }
}

/* 调试信息样式 */
.debug-info {
  margin-bottom: 20px;
  background: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
}

.debug-order-info {
  background: #f5f7fa;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 13px;
  color: #333;
  border-left: 4px solid #409EFF;
}

.debug-order-info p {
  margin: 5px 0;
}

.order-status {
  display: flex;
  align-items: center;
}

.status-tag {
  font-weight: bold;
  padding: 4px 10px;
  border-radius: 12px;
}

.good-info {
  display: flex;
  flex: 1;
  justify-content: space-between;
  align-items: flex-start;
}

.good-name-container {
  flex: 1;
  padding-right: 10px;
}
</style> 